package cn.dida.controller;

import cn.dida.model.Pageable;
import cn.dida.model.UserSession;
import cn.dida.service.SalesmanCashService;
import cn.dida.service.SalesmanScanService;
import cn.dida.util.DateUtils;
import cn.dida.util.ExcelUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;


@Controller
@RequestMapping("/salesmanScan")
public class SalesmanScanController extends BaseController {

    @Autowired
    private SalesmanScanService scanService;

   
    @GetMapping("/list")
    public ModelAndView queryList(HttpServletRequest request,String qrcode, String proName, String saleman, Long timeLimitStart, Long timeLimitEnd , Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
        page = (page == null || page < 1) ? 1 : page;
        proName = StringUtils.trimToNull(proName);
        saleman = StringUtils.trimToNull(saleman);
        Pageable<Map<String,Object>> result = scanService.queryList(userSession.getCompanyId(),qrcode,proName,saleman,timeLimitStart,timeLimitEnd,page);
        model.put("salescanlog", result);
        model.put("proName", proName);
        model.put("saleman", saleman);
        model.put("qrcode", qrcode);
        model.put("timeLimitStart", timeLimitStart);
        model.put("timeLimitEnd", timeLimitEnd);
        return new ModelAndView("salesman_scanlog").addAllObjects(model);
    }

    
    @GetMapping("/export")
    public ModelAndView export(HttpServletRequest request, HttpServletResponse response,String qrcode, String proName, String saleman, Long timeLimitStart, Long timeLimitEnd) throws Exception {
        UserSession userSession = getUserSession(request);

        List<Map<String,Object>> exportList = scanService.exportList(userSession.getCompanyId(),qrcode, proName, saleman,timeLimitStart,timeLimitEnd);

        String fileName = "促销记录数据导出" + DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(exportList.size());

        Map<String, Object> fmap = null;
        for (Map<String,Object> obj : exportList) {
            fmap = obj;
            fmap.put("c_time",DateUtils.transferLongToDate("yyyy-MM-dd HH:mm:ss", (Long)obj.get("c_time")));
            list.add(fmap);
        }
      
        String columnNames[] = {"二维码编号",  "促销员姓名", "产品编码","产品名称",  "手机号",  "状态","规则状态","提现状态","扫码时间"};//列名
        String keys[] = {"id", "salesname", "procode","proname",  "phone", "state","payrulesate","txstate","c_time"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
                bos.flush();
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

        return null;
    }

   
}
